<script setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { ref } from 'vue'
	import { getAddress, addAddress, updateAddress, delAddress } from '@/api/user'
	
	const loading = ref(false)
	const uForm = ref(null)
	const form = ref({
		addrId: null,
		orgId: [510000, 510100, 510107],
		orgName: '',
		addr: '',
		contactPerson: '',
		contactPhone: '',
		defaultAddress: [0]
	})
	const rules = ref({
		orgName: [
			{required: true, message: '请选择所在地区', trigger: ['blur', 'change']}
		],
		addr: [
			{required: true, message: '请输入门牌号', trigger: ['blur', 'change']}
		],
		contactPerson: [
			{required: true, message: '请输入姓名', trigger: 'blur'}
		],
		contactPhone: [
			{required: true, message: '请输入联系电话', trigger: 'blur'},
			{
				validator: (rule, value, callback) => {
					return uni.$uv.test.mobile(value)
				},
				message: '联系电话格式错误',
				trigger: 'blur'
			}
		]
	})
	
	function getData(id) {
		loading.value = true
		getAddress(id).then(res => {
			let data = res.result || {}
			data.defaultAddress = [data.defaultAddress]
			form.value = data
			loading.value = false
		}).catch(() => loading.value = false)
	}
	function cityChange(e){
		uni.chooseLocation({
			success: (res) => {
				let latitude = res.latitude
				let longitude = res.longitude
				let key = 'Z4JBZ-YVGRU-AN4VL-G2AK3-TADFO-UNFK5'; // 替换为你的腾讯地图API密钥
				let url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}`;
				wx.request({
					url: url,
					success: (response) => {
						let data = response.data
						let result = data.result
						if (data.status === 0) {
							let address = result.address_component
							form.value.orgId = result.address_reference.town.id
							form.value.orgName = address.province + address.city + address.district + result.address_reference.town.title
							form.value.addr = address.street_number || address.street
						}
					}
				})
			}
		})
	}
	function submit() {
		uForm.value.validate().then(() => {
			loading.value = true
			let params = uni.$uv.deepClone(form.value)
			params.defaultAddress = params.defaultAddress[0]? params.defaultAddress[0] : 0
			if(form.value.addrId) {
				updateAddress(params).then(res => {
					uni.showToast({
						icon: 'success',
						title: '修改成功'
					})
					setTimeout(()=>{uni.navigateBack()}, 200)
				}).catch(() => loading.value = false)
			} else {
				addAddress(params).then(res => {
					uni.showToast({
						icon: 'success',
						title: '保存成功'
					})
					setTimeout(()=>{uni.navigateBack()}, 200)
				}).catch(() => loading.value = false)
			}
		})
	}
	function del() {
		loading.value = true
		delAddress([form.value.addrId]).then(res => {
			uni.showToast({
				icon: 'success',
				title: '删除成功'
			})
			setTimeout(()=>{uni.navigateBack()}, 200)
		}).catch(() => loading.value = false)
	}
	
	onLoad((option) => {
		if(option.id){
			uni.setNavigationBarTitle({
				title: '编辑收货地址'
			})
			getData(option.id)
		}else{
			uni.setNavigationBarTitle({
				title: '添加收货地址'
			})
		}
	})
</script>

<template>
	<view class="app-container">
		<uv-form :model="form" :rules="rules" ref="uForm" labelWidth="auto">
			<view class="form-box">
				<uv-form-item label="所在地区" prop="orgName" required borderBottom>
					<view class="custom-content" @click="cityChange">
						<text :class="form.orgName? '' : 'text-no'">{{form.orgName? form.orgName : '请选择所在地区'}}</text>
						<uv-icon name="arrow-right" color="#54504D" size="30" />
					</view>
				</uv-form-item>
				<uv-form-item label="门牌号" prop="addr" required borderBottom>
					<uv-input v-model="form.addr" placeholder="请输入门牌号" border="none" inputAlign="right" maxlength="32" clearable />
				</uv-form-item>
				<uv-form-item label="姓名" prop="contactPerson" required borderBottom>
					<uv-input v-model="form.contactPerson" placeholder="请输入姓名" border="none" inputAlign="right" maxlength="32" clearable />
				</uv-form-item>
				<uv-form-item label="联系电话" prop="contactPhone" required borderBottom>
					<uv-input type="number" v-model="form.contactPhone" placeholder="请输入联系电话" border="none" inputAlign="right" maxlength="11" clearable />
				</uv-form-item>
				<uv-form-item label="">
					<uv-checkbox-group shape="circle" v-model="form.defaultAddress" size="34" iconSize="34" labelSize="30" :customStyle="{flex: '0 0 auto'}">
						<uv-checkbox :name="1" label="设置为默认地址" activeColor="#FF3E49" ></uv-checkbox>
					</uv-checkbox-group>
				</uv-form-item>
			</view>
		</uv-form>
		<view class="form-bottom">
			<uv-button color="#FF3E49" text="保存地址" @click="submit" :disabled="loading"></uv-button>
			<uv-button type="info" text="删除地址" @click="del" :disabled="loading" v-if="form.addrId"></uv-button>
		</view>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		.form-box{
			margin: 24rpx;
			background-color: #fff;
			padding: 0 20rpx;
			border-radius: 24rpx;
			.custom-content{
				padding-left: 24rpx;
				display: flex;
				justify-content: flex-end;
				gap: 10rpx;
			}
			.text-no{
				color: #808080;
			}
			::v-deep .uv-form-item__body__left__content__required{
				left: unset;
				right: -8rpx;
			}
		}
		.form-bottom{
			margin: 0 24rpx;
			display: flex;
			flex-direction: column;
			gap: 16rpx;
		}
	}
</style>